/**
 * 
 */

var index=angular.module('photoCenter',['ngRoute','ngResource','akoenig.deckgrid','infinite-scroll']);

var page = 2;
var size = 10;
var current="";
var upload="";

var directoryController=function($http,$scope,TipService){
    $scope._index=0;
    
    $scope.scorll=false;
    $scope.current="";
    $scope.tipService=TipService;
    
    $scope.start=0;  //照片墙开始前的序号
    $scope.end=0;   //本次照片墙循环的长度
    
    $http.get('directory/getDirectories').then(function(data){
        $scope.directory=eval(data.data);
    });
    
    $scope.click=function(name){
    	$scope.current=name;
    	current=name;
    	upload='photo/upload?path='+current;
    	page=2;
    	_index=0;
    	$scope.photos=[];
    	$scope.scroll=false;
    	 $scope.start=0;
    	
    	$('.collapse').collapse('toggle');
    	
    	$http.get('directory/getFiles?path='+name+'&page=1'+'&size='+size).then(function(data){
    		var temp=eval(data.data);
    		if(temp!=undefined && temp.length>0){
    			for (var i = 0; i < temp.length; i++) {
    				$scope.photos.push(temp[i]);
    			}
    		}
    		$scope.end=temp.length;
        });
    };
    
    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
    	'use strict';
       var length=$scope.end;
       for (var i=0;i<length;i++){
    	   if($scope.photos[$scope.start+i].flag=='1'){
    		   const player = LivePhotosKit.Player(document.getElementById('livephoto'+($scope.start+i)));
    		   player.photoSrc =$scope.photos[$scope.start+i].thumpath;
    		   player.videoSrc =$scope.photos[$scope.start+i].videoUrl;
    	   }
    	   
       }
       
       
       $scope.start=$scope.end;
       $scope.scroll=false;
   });

    
    $scope.loadMore = function() {
    	if($scope.scorll)
    		return;
    	 $scope.scroll=true;
         $http.get('directory/getFiles?path='+$scope.current+'&page='+page+'&size='+size).then(function(data){
             //$scope.images = [];
             $scope.results = eval(data.data);
             //if ($scope.results.length == 73) {
               //  $scope.text = "内容已经全部加载完毕"
             //}
             if($scope.results!=undefined && $scope.results.length>0){
	             for (var i = 0; i < $scope.results.length; i++) {
	                 $scope.photos.push($scope.results[i]);
	             }
	             $scope.end=$scope.results.length;
	        	 page++;
             }
         });
      };

    $scope.showBig=function(index){
    	//$('#loadingModal').modal({backdrop: 'static', keyboard: false});
    	var time = new Date().getTime(); 
        _index=index;
        $scope.modalPhoto=$scope.photos[index];
        $('#photoName').html($scope.photos[_index].name);
        if($scope.modalPhoto.flag=="0"){
            $("#imgInModalID").attr('src',$scope.photos[_index].thumpath); 
        	//$scope.$apply(function () {
        	//      $scope.modalPhoto.thumpath =  $scope.modalPhoto.thumpath + '?' + time;  //增加随机参数时间可强制刷新
        	//});
        }
        $scope.reload();
       $('#imgModal').modal({
            backdrop: true
        });
    }

    
    $scope.isActive=function(path){
    	return $scope.current===path;	
    }
    
    $scope.uploadDown = function () {
		var fd = new FormData();
		var files =  document.querySelector('input[name="files"]').files;
		 for (var i=0; i<files.length; i++) {
			 fd.append("files", files[i]);
    	 }
		 fd.append("path", $scope.current);
		$http({
    	        method:'POST',
    	        url  : 'photo/upload',
    	        data: fd,
    	        headers: {'Content-Type':undefined},
    	        transformRequest: angular.identity
    	      }).then(function(data){
    				var d=eval(data.data);
    				if(d.flag){
    					$('#uploadModal').modal('hide');
    					TipService.setMessage('上传成功', "success");
    				}
    			});
      }
    
    $scope.upload=function(){
    	if($scope.current==""){
    		return;
    	}
    	 $('#uploadModal').modal({
             backdrop: true
         });
    }
    
    $scope.add=function(){
    	$('#typeModal').modal({
    		 backdrop: true
    	});
    }
    
    $scope.saveAdd=function(){
    	debugger
    	var fd = new FormData();
    	fd.append("name",$scope.newType);
    	$http({
	        method:'POST',
	        url  : 'directory/add?name='+encodeURI($scope.newType),
	        data: fd,
	        transformRequest: angular.identity
	      }).then(function(data){
				var d=eval(data.data);
				if(d.flag){
					$('#typeModal').modal('hide');
					TipService.setMessage('新建成功', "success");
					$scope.directory.push({'name':$scope.newType,'url':d.url});
					$scope.newType="";
					
				}
			});
    }
    
    $scope.closeAdd=function(){
		$('#typeModal').modal('hide');
    }
    
    
    $('#uploadModal').on('hide.bs.modal', function () {
    	 debugger
    	 angular.element('#fileupload').fileinput('clear')
    	});
    
   
    $scope.reload=function(){
    	var img = new Image();
        img.src = $scope.modalPhoto.url;
        img.onload = $scope.changeUrl(img);
    }
    
    $scope.changeUrl=function(img){
    	 $("#imgInModalID").attr('src',img.src)	; 
    }
    

};

index.directive('ulLeft',function(){
	var menuObject={
			templateUrl:'template/directory.html',
			replace:true,
            controller:directoryController,
            restrict :'EA'
	};
	return menuObject;
});

index.directive('onFinishRenderFilters', function ($timeout) {
	  return {
	    restrict: 'A',
	    link: function(scope, element, attr) {
	      if (scope.$last === true) {
	        $timeout(function() {
	          scope.$emit('ngRepeatFinished');
	        });
	      }
	    }
	  };
	});

index.directive('inputOnChange', function(){
	  return{
		    restrict: 'A',
		    link: function (scope, element, attrs) {
		      var onChangeFunc = scope.$eval(attrs.inputOnChange);
		      element.bind('change', onChangeFunc);
		    }
		  }
		});

index.factory('TipService', ['$timeout', function($timeout) {
    return {
        message : null,
        type : null,
        setMessage : function(msg,type){

            this.message = msg;
            this.type = type;

            //提示框显示最多1秒消失
            var _self = this;
            $timeout(function(){
                _self.clear();
            },1000);
        },
        clear : function(){
            this.message = null;
            this.type = null;
        }
    };
}]);

index.directive('alertBar',[function(){

    return {
        restrict: 'EA',
        templateUrl: 'template/tip.html',
        scope : {
            message : "=",
            type : "="
        },
        link: function(scope, element, attrs){
            scope.hideAlert = function() {
                scope.message = null;
                scope.type = null;
            };

        }
    };
}]);

index.controller("uploadCtrl",function($http,$scope,TipService){
	$scope.uploads={};

	$("#fileupload").fileinput({
		 allowedFileExtensions: ["jpg", "png","jpeg"],
		 uploadUrl:'photo/upload',
		 maxFileCount: 10,
		 language: 'zh',
		 overwriteInitial: false,
		 resizeImage: false,
		 showCaption: true,//是否显示标题
		 showPreview :true, //是否显示预览
		 showUpload:true, //是否显示上传按钮
	    showRemove :true, //显示移除按钮
	    uploadAsync: true, //默认异步上传
	    dropZoneEnabled: false,
	    uploadExtraData: function(previewId, index) {   //额外参数的关键点
            var obj = {'path':$scope.current};
            return obj;
        }
	 });
	
	$("#fileupload").on("fileuploaded", function (event, data, previewId, index) {
			//上传完毕事件
		var data = data.response;
		$scope.uploads[previewId]=data.items[0].name;
		//获取现有的index
		//$scope.photos
		return;
		
	});
	
	$("#fileupload").on("filesuccessremove", function (event, data, previewId, index) { 
	   //从后台删除
		var name=$scope.uploads[data];
		$http({
	    	        method:'DELETE',
	    	        url  : 'photo/delete?name='+name+"&path="+$scope.current
	    	      }).then(function(data){
	    				var d=eval(data.data);
	    				if(d.flag){
	    					//$('#uploadModal').modal('hide');
	    					TipService.setMessage('删除成功', "success");
	    					//$scope.uploads.splice(previewId,1);
	    				}
	    			});
	});


});

index.controller("imgCtrl",function($http,$scope,TipService){
	var carousels = $("#imgInModalID");  //获取的轮播图
    var startX,endX,finalMove;
    var diviation = 60;  //让手指滑动一定距离轮播图才工作
    
    carousels.on("touchstart",function(event) {
        // console.log(event.originalEvent.touches[0].pageX);
         startX = event.originalEvent.touches[0].pageX;//获取手指接触屏幕时的位置
     });
     carousels.on("touchmove",function(event) {
        // console.log(event.originalEvent.touches[0].pageX);
         endX = event.originalEvent.touches[0].pageX;//手指滑动时该值一直刷新，当手指离开时保留最后一次手指的位置
     });
     carousels.on("touchend",function(event) {
         //console.log(event.originalEvent.touches[0].pageX);
         finalMove = Math.abs(startX - endX) - diviation;
         if(finalMove > 0 && (startX - endX) > 0) {//如果手指滑动方向向左，轮播图向右播放一张图片
             //$(this).carousel('next');
         	$scope.next();
         }
         else if (finalMove > 0 && (startX - endX) < 0) {
             $scope.pre();
         }
     });
     

     $scope.next=function(){
     	_index++;
     	if(_index>$scope.photos.length){
     		$scope.loadMore();
     	}
     	$scope.$parent.modalPhoto=$scope.photos[_index];
     	$('#photoName').text($scope.photos[_index].name);
     	$("#imgInModalID").attr('src',$scope.photos[_index].thumpath); 
     	$scope.reload();
     }
     
     $scope.pre=function(){
     	_index--;
     	if(_index==-1){
     		_index=0;
     	}
        $scope.$parent.modalPhoto=$scope.photos[_index];
     	$('#photoName').text($scope.photos[_index].name);
        $("#imgInModalID").attr('src',$scope.photos[_index].thumpath); 
        $scope.reload();
     }
     
     
     $scope.dele=function(){
     	$http({
 	    	        method:'DELETE',
 	    	        url  : 'photo/delete?name='+$scope.modalPhoto.name+"&path="+$scope.current
 	    	      }).then(function(data){
 	    				var d=eval(data.data);
 	    				if(d.flag){
 	    					TipService.setMessage('删除成功', "success");
 	    					$scope.$parent.photos.splice(_index,1);
 	    					$scope.start=$scope.start-1;//start 应该永远指向 照片墙的最后一张，这里删掉了1张，就应该前移1张
 	    					//$scope.uploads.splice(previewId,1);
 	    					//先刷新当前页数，然后再展示下一条
 	    					//$scope.$parent.scroll=true;
 	    					$http.get('directory/getFiles?path='+$scope.current+'&page='+page+'&size='+size).then(function(data){
 	    			             //$scope.images = [];
 	    			             $scope.results = eval(data.data);
 	    			            if($scope.results!=undefined && $scope.results.size>0){
 	    			             //去掉末页的9条
 	    			            $scope.$parent.photos.splice(page*size,9);
 	    			           $scope.start=$scope.start-9;//start 应该永远指向 照片墙的最后一张，这里删掉了9张，就应该前移9张
 	    			           $scope.end= $scope.results.length;
 	    			            	for (var i = 0; i < $scope.results.length; i++) {
 	 	    			                 $scope.photos.push($scope.results[i]);
 	 	    			             }
 	    			            }
 	    			             //$scope.$parent.scroll=false;
 	    			             //切换到下一条
 	    			             $scope.next();
 	    			         });
 	    				}
 	    			});
     }

});


 
